package com.yy.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yy.dto.SetmealDto;
import com.yy.entity.Dish;
import com.yy.entity.DishFlavor;
import com.yy.entity.Setmeal;
import com.yy.entity.SetmealDish;
import com.yy.mapper.SetmealMapper;
import com.yy.service.CategoryService;
import com.yy.service.SetmealDishService;
import com.yy.service.SetmealService;
import com.yy.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * create by KongFuning on 2022/8/2
 */
@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /*
    * 分页
    * */
    @Override
    public R pageSetmeal(Integer page, Integer pageSize, String name) {
        // 套餐基本信息
        Page<Setmeal> pageSetmeal = new Page<>(page,pageSize);
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getIsDeleted,0);
        queryWrapper.like(StrUtil.isNotEmpty(name),Setmeal::getName,name);
        page(pageSetmeal, queryWrapper);
        // ------------------------------------------------------------------
        // 获取套餐对应的菜品list和分类名称 封装进Page<SetmealDto>
        Page<SetmealDto> pageSetmealDto = new Page<>(page,pageSize);
        // 将套餐基本信息拷贝进pageSetmealDto
        BeanUtil.copyProperties(pageSetmeal,pageSetmealDto,"records");
        // 取出pageSetmeal中的records
        List<Setmeal> setmealList = pageSetmeal.getRecords();
        // 对每一个Setmeal进行处理，转化成pageSetmealDto对象，并给套餐对应的菜品list和分类名称赋值
        List<SetmealDto> setmealDtoList = setmealList.stream().map((item) ->{
            SetmealDto setmealDto = new SetmealDto();
            BeanUtil.copyProperties(item,setmealDto);
            // 查询分类名称
            String categoryName = categoryService.getById(item.getCategoryId()).getName();
            setmealDto.setCategoryName(categoryName);
            // 查询套餐对应的菜品list
            List<SetmealDish> list = setmealDishService.query().eq("setmeal_id", item.getId()).list();
            setmealDto.setSetmealDishes(list);
            return setmealDto;
        }).collect(Collectors.toList());
        pageSetmealDto.setRecords(setmealDtoList);
        return R.success(pageSetmealDto);
    }

    /*
     * 添加套餐
     * */
    @Override
    @Transactional
    public R saveSetmeal(SetmealDto setmealDto) {
        // 保存套餐基本信息
        save(setmealDto);

        // 获取套餐对应的菜品信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        // 给每一个SetmealDish设置上setmeal_id
        setmealDishes = setmealDishes.stream().map((item) ->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        // 保存菜品信息到setmeal_dish
        setmealDishService.saveBatch(setmealDishes);

        // 清理redis缓存
        stringRedisTemplate.delete("setmeal:categoryId:" + setmealDto.getCategoryId());
        return R.success("新增套餐成功！");
    }

    /*
     * 修改套餐 回显数据
     * */
    @Override
    public R toUpdateSetmeal(String setmealId) {
        // 根据套餐id查询套餐基本信息
        Setmeal setmeal = getById(setmealId);

        // 将setmeal对象拷贝为setmealDto对象
        SetmealDto setmealDto = new SetmealDto();
        BeanUtil.copyProperties(setmeal,setmealDto);
        // 给setmealDto对象设置categoryName分类名称
        String categoryId = getById(setmealId).getCategoryId();
        String categoryName = categoryService.getById(categoryId).getName();
        setmealDto.setCategoryName(categoryName);
        // 给setmealDto对象设置setmealDishes改套餐下对应的菜品list
        List<SetmealDish> setmealDishList = setmealDishService.query().eq(setmealId != null, "setmeal_id", setmealId).list();
        setmealDto.setSetmealDishes(setmealDishList);
        return R.success(setmealDto);
    }

    /*
     * 修改套餐
     * */
    @Override
    @Transactional
    public R updateSetmeal(SetmealDto setmealDto) {
        // 更新套餐的基本信息
        updateById(setmealDto);

        // 清理当前套餐对应的菜品 —— setmeal_dish表的delete 操作
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,setmealDto.getId());
        setmealDishService.remove(queryWrapper);

        // 添加当前提交过来的菜品数据 —— setmeal_dish表的insert 操作
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);

        // 清理redis缓存
        stringRedisTemplate.delete("setmeal:categoryId:" + setmealDto.getCategoryId());
        return R.success("更新套餐成功！");
    }

    @Override
    public R isSale(Integer status, String ids) {
        Setmeal setmeal = new Setmeal();
        setmeal.setStatus(status);
        setmeal.setId(ids);
        updateById(setmeal);
        return R.success("套餐状态更改成功！");
    }

    @Override
    public R deleteSetmeal(String ids) {
        // 逻辑删除
        Setmeal setmeal = getById(ids);
        setmeal.setIsDeleted(1);
        updateById(setmeal);

        // 清理redis缓存
        stringRedisTemplate.delete("setmeal:categoryId:" + setmeal.getCategoryId());
        return R.success("套餐删除成功！");
    }

    @Override
    public R setmealDetail(Setmeal setmeal) {
        List<Setmeal> setmealDetailList = new ArrayList<>();
        // 1、先从redis缓存中查询数据
        String setmealJson = stringRedisTemplate.opsForValue().get("setmeal:categoryId:" + setmeal.getCategoryId());
        // 2、如果缓存中存在，则直接返回
        if(StrUtil.isNotEmpty(setmealJson)){
            setmealDetailList = JSONUtil.toList(setmealJson, Setmeal.class);
            return R.success(setmealDetailList);
        }
        // 3、不存在，查询数据库，并写入缓存
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.eq(Setmeal::getIsDeleted,0);
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        setmealDetailList = list(queryWrapper);
        // 写入缓存
        stringRedisTemplate.opsForValue().set("setmeal:categoryId:" + setmeal.getCategoryId(),JSONUtil.toJsonStr(setmealDetailList));
        return R.success(setmealDetailList);
    }

    /*
     * 根据id查询套餐
     * */
    @Override
    public R getSetmealById(String id) {
        Setmeal setmeal = getById(id);
        return R.success(setmeal);
    }

}
